package com.handydata.antifraud.ws.dap;

import com.alibaba.fastjson.JSONObject;
import com.handydata.antifraud.annotation.Comment;
import com.handydata.antifraud.common.constant.DataSourceCode;
import com.handydata.antifraud.common.exception.WsInvokeException;
import com.handydata.antifraud.to.dap.DataZhiChengAfuScoreReqTO;
import com.handydata.antifraud.to.dap.DataZhiChengAfuScoreResTO;
import com.handydata.antifraud.util.DateUtil;
import com.handydata.antifraud.util.encrypt.Md5Utils;
import com.handydata.antifraud.ws.WsInvocationService;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

import java.util.Date;

/**
 * 宜信-至诚阿福-综合评分
 *
 */
@Slf4j
@Service("dataZhiChengAfuScoreWsService")
@Comment("宜信至诚阿福")
public class DataZhiChengAfuScoreWsServiceImpl extends DataPlatformWsService<DataZhiChengAfuScoreReqTO, DataZhiChengAfuScoreResTO>
	implements WsInvocationService<DataZhiChengAfuScoreReqTO, DataZhiChengAfuScoreResTO> {

	@Override
	public DataZhiChengAfuScoreResTO query(DataZhiChengAfuScoreReqTO req) throws WsInvokeException {
		log.info("宜信-至诚阿福请求参数 {}", req);
		DataZhiChengAfuScoreResTO resTO = new DataZhiChengAfuScoreResTO();
		if (StringUtils.isEmpty(req.getIdCard())) {
			log.error("宜信-至诚阿福参数校验 {}", "cid为空");
			resTO.setResCode("1111");
			resTO.setResMsg("宜信-至诚阿福接口cid参数为空");
			return resTO;
		}
		if (StringUtils.isEmpty(req.getName())) {
			log.error("宜信-至诚阿福参数校验 {}", "name为空");
			resTO.setResCode("1111");
			resTO.setResMsg("宜信-至诚阿福接口name参数为空");
			return resTO;
		}
		if (StringUtils.isEmpty(req.getPhoneNum())) {
			log.error("宜信-至诚阿福参数校验 {}", "phone为空");
			resTO.setResCode("1111");
			resTO.setResMsg("宜信-至诚阿福接口phone参数为空");
			return resTO;
		}
		this.dataType = DataSourceCode.DATA_ZHI_CHENG_A_FU.getCode();
		resTO = executeQuery(req);
		// 行内压测挡板处理
//		try {
//			Thread.sleep(950);
//		} catch (InterruptedException e) {
//			e.printStackTrace();
//		}
		//模拟数据源返回成功结果      success
		// success 1
//		String data = "{\"resCode\":\"0000\",\"resMsg\":\"查询成功\",\"resData\":{\"compositeScore\":\"437\",\"decisionSuggest\":\"5\"}}";
		// fail 2
//			String data = "{\"resCode\":\"0000\",\"resMsg\":\"查询成功\",\"resData\":{\"compositeScore\":\"621\",\"decisionSuggest\":\"5\"}}";
		// 3
//		String data = "{\"resCode\":\"0002\",\"resMsg\":\"身份格式错误\"}";
//		JSONObject jasonObject = JSONObject.parseObject(data);
//		if ("0000".equals(jasonObject.getString("resCode"))) {
//			JSONObject resData = jasonObject.getJSONObject("resData"); 
//			if (resData != null) {
//				resTO.setCompositeScore(resData.getInteger("compositeScore"));
//			}
//		} else {
//			resTO.setCompositeScore(Integer.MAX_VALUE);
//		}
//		resTO.setResCode((String)jasonObject.get("resCode"));
//		resTO.setResMsg((String)jasonObject.get("resMsg"));
		return resTO;
	}
	
	@Override
	protected String createQueryXml(DataZhiChengAfuScoreReqTO req) {
		StringBuilder xml = new StringBuilder();
        xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>");
		xml.append("<subatm>");
		xml.append("<application>GwBiz.Req</application>");
		xml.append("<version>1.0.0</version>");
		xml.append("<sendTime>").append(DateUtil.now14()).append("</sendTime>");
		xml.append("<transCode>300671</transCode>");
		xml.append("<channelId>").append(encryInfo.getChannelId()).append("</channelId>");
		xml.append("<channelOrderId>").append(DateUtil.now17()).append("</channelOrderId>");
//		xml.append("<name>").append(req.getName()).append("</name>");
//		xml.append("<cid>").append(req.getIdCard()).append("</cid>");
//		xml.append("<phone>").append(req.getPhoneNum()).append("</phone>");
		xml.append("<cid>").append(Md5Utils.md5ToHexStr(req.getIdCard())).append("</cid>");
		xml.append("<name>").append(Md5Utils.md5ToHexStr(req.getName())).append("</name>");
		xml.append("<phone>").append(Md5Utils.md5ToHexStr(req.getPhoneNum())).append("</phone>");
		xml.append("<queryReason>").append("LOAN_AUDIT").append("</queryReason>");
		xml.append("<corpName>").append(null2Empty(req.getUnitName())).append("</corpName>");
		xml.append("</subatm>");
		req.setQueryXml(xml.toString());
		return xml.toString();
	}
	
	@Override
	protected DataZhiChengAfuScoreResTO parseResultAndSave(String resultXml,	String orderId, Date createDate) {
		log.info("调用宜信-至诚阿福接口返回报文：{}", resultXml);
		DataZhiChengAfuScoreResTO resTO = new DataZhiChengAfuScoreResTO();
		try{
			// 解析xml，保存本地DB
			JSONObject jasonObject = JSONObject.parseObject(resultXml);
			if ("0000".equals(jasonObject.getString("resCode"))) {
    			JSONObject resData = jasonObject.getJSONObject("resData"); 
				if (resData != null) {
					resTO.setCompositeScore(resData.getInteger("compositeScore") == null ? Integer.MAX_VALUE : resData.getInteger("compositeScore"));
				}
    		}else{
				resTO.setCompositeScore(Integer.MAX_VALUE);
			}
			resTO.setResCode((String)jasonObject.get("resCode"));
			resTO.setResMsg((String)jasonObject.get("resMsg"));
		} catch (Exception e){
			log.info("调用宜信-至诚阿福接口返回报文解析异常：{}", e);
			resTO.setResCode("1111");
			resTO.setResMsg("调用宜信-至诚阿福接口返回报文解析异常");
		}
		log.info("调用宜信-至诚阿福接口返回结果：{}", JSONObject.toJSONString(resTO));
		return resTO;
	}
	
	private String null2Empty(String str) {
		if(str == null) {
			return "";
		}
		return str;
	}
	
	@SuppressWarnings("unchecked")
	@PostConstruct
	@Override
	public void register() {
		registerToWsServiceFactory(this, DataZhiChengAfuScoreReqTO.class);
	}
	
}

